import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
import './index.scss'
import { App, Button, Card, Form, Input, message, Row, Select, Space, Table, Tag } from "antd";
import type { OptionGroupType, OptionGroupDto, OptionType } from "@/types";
import { useForm } from "antd/es/form/Form";
import { addOptionGroup, deleteOptionGroup, getInterviewOptions, queryOptionGroup } from "@/apis/commonService";
import { filterOptionsByOptionGroupKey } from "@/utils/common";
import { EditOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import dayjs from "dayjs";
import OptionGroupForm from "@/components/OptionForm/OptionGroupForm";

const OptionGroup = forwardRef((props, ref) => {
    const { modal } = App.useApp();
    // 表格数据
    const [tableData,setTableData] = useState<OptionGroupType[]>([]);
    // 总记录数
    const [total,setTotal] = useState<number>(0);
    // 查询条件
    const [queryForm,setQueryForm] = useState<OptionGroupDto>({
        status: 1,
        current: 1,
        size: 6
    });
    // 查询表单标识
    const [form] = Form.useForm();
    // 组件标识
    const OptionGroupFormRef = useRef(null);

    const columns = [
        {
            title: '组别名称',
            dataIndex: 'groupDesc'
        },
        {
            title: '组别类型',
            dataIndex: 'groupKey',
            render: (value: string) => {
                return <Button color="primary" variant="link" onClick={() => toSelectOptionPage(value)}>{value}</Button>
            }
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: (value: number,record: OptionGroupType) => {
                return (
                    <Tag color={ record.status === 1 ? 'processing' : 'error' }>
                        {
                            record.status === 1 ? '正常' : '停用'
                        }
                    </Tag>
                )
            }
        },
        {
            title: '备注',
            dataIndex: 'remark'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            render: (createTime: string,record: OptionGroupType) => {
                return (
                    <span>{ dayjs(createTime).format('YYYY-MM-DD HH:mm:ss') }</span>
                )
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record: OptionGroupType) => (
            <Space size="middle">
                <Button onClick={() => {OptionGroupFormRef.current.open(record)}} type="primary" icon={<EditOutlined />}>修改</Button>
            </Space>
            ),
        },
    ];

    // 加载中标识
    const [loading, setLoading] = useState(false);
    // 当前选中的数据行id
    const [selectDataIds,setSelectDataIds] = useState<string[]>([]);
    // 当前选中的数据
    const [selectedDatas,setSelectDatas] = useState<OptionGroupType[]>([]);
    
    /** 表格选中回调  */
    const tabSelectChange = (selectedRowKeys: React.Key[], selectedRows: OptionGroupType[]) => {
        setSelectDataIds(selectedRowKeys as string[]);
        setSelectDatas(selectedRows as OptionGroupType[]);
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    }

    /** 改变查询条件  */
    const changeSeleteCondition = (params: OptionGroupDto) => {
        setQueryForm(params);
    }

    /** 查询  */
    const queryTableData = async () => {
        try {
            setLoading(true);            
            const res = await queryOptionGroup(queryForm);
            console.log("查询结果Res====>",res);
            // 若当前查询的记录数为0 且当前页数不为1 则当前页数减少1页后重新查询
            if (res.data.records.length === 0 && queryForm.current != 1) {
                setQueryForm({
                    ...queryForm,
                    current: queryForm.current - 1
                })
            }
            setTableData(res.data.records);
            setTotal(res.data.total);
        } catch (error) {
            console.log(error);
        }finally{
            setLoading(false);
        }
    }

    /** 新增 */
    const add = async () => {
        OptionGroupFormRef.current.open();
    }

    /** 删除 */
    const deleteTableData = async () => {
        if (selectedDatas.length === 0) {
            message.warning('请先选择数据再进行操作！')
            return;
        }
        const deleteGourpKeyList: string[] =  selectedDatas.map(item => item.groupKey) as string[];
        modal.confirm({
            title: '温馨提示',
            content: '是否删除选中的数据？',
            okText: '确认',
            cancelText: '取消',
            async onOk(){
               const res = await deleteOptionGroup(deleteGourpKeyList);
                if (res.code === 200) {
                    message.success("删除成功！");
                    await queryTableData();
                }else {
                    message.error(res.msg);
                } 
            },
            onCancel: () => {

            }
        })
    }

    /** 面试评价  */
    const updateTableData = (val: OptionGroupType) => {
        OptionGroupFormRef.current.open(val);
    }

    /** 跳转到字典页面  */
    const navigate = useNavigate();
    const toSelectOptionPage = (optionGroupKey: string) => {
        navigate('/selectOption', { 
            state: { 
                optionGroupKey: optionGroupKey 
            } 
        });
    }

    /** 页面初始化 或 查询条件发生改变时 调用查询 */
    useEffect(() => {
        queryTableData();
    },[queryForm])
    
    return (
        <div className="option-group">
            <Card className="card" title="查询条件">
                <Form
                    form={form}
                    layout="inline"
                    name="option-group"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ width: '100%' }}
                    initialValues={{ status: queryForm.status }}
                    onFinish={(val) => changeSeleteCondition({...queryForm,...val})}
                    autoComplete="off"
                >
                    <Row style={{ width: '100%' }}>
                        <Form.Item<OptionGroupType>
                            label="组别名称"
                            name="groupDesc"
                        >
                            <Input placeholder="请输入组别名称"/>
                        
                        </Form.Item>
                        
                        <Form.Item<OptionGroupType>
                            label="组别类型"
                            name="groupKey"
                        >
                            <Input placeholder="请输入组别类型"/>
                        </Form.Item>

                        <Form.Item<OptionGroupType>
                            label="状态"
                            name="status"
                        >
                            <Select
                                placeholder="请选择"
                                allowClear
                                style={{ width: 200 }}
                                options={[
                                    {
                                        label: '启用',
                                        value: 1
                                    },
                                    {
                                        label: '禁用',
                                        value: 0
                                    }
                                ]}
                            />
                        </Form.Item>
                    </Row>

                    <Row justify='end' style={{ width: '100%',marginTop: '20px' }}>
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="button" onClick={add}>
                                新增
                            </Button>
                        </Form.Item>
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="button" onClick={deleteTableData}>
                                删除
                            </Button>
                        </Form.Item>
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                        </Form.Item>
                    </Row>
                </Form>
            </Card>

            <Card className="card" title="查询结果">
                <Table
                    rowKey="id"
                    loading={loading} 
                    dataSource={tableData} 
                    columns={columns}
                    rowSelection={{ type: 'checkbox',onChange: tabSelectChange,selectedRowKeys: selectDataIds,preserveSelectedRowKeys: true }}
                    pagination={{
                        showQuickJumper: true,
                        total: total,
                        showTotal: (total) => `共 ${total} 条数据`,
                        current: queryForm.current,
                        pageSize: queryForm.size,
                        showSizeChanger: true,
                        onChange: (current,size) => changeSeleteCondition({...form.getFieldsValue(),current,size}),
                        pageSizeOptions: [6,10,20,50,100]
                    }}  
                />
            </Card>
            <OptionGroupForm ref={OptionGroupFormRef} reQuery={() => queryTableData()}></OptionGroupForm>
        </div>
    )

    useImperativeHandle(ref, () => ({
    }));
});

export default OptionGroup;